<?php

namespace api\behaviors\actions;

use Yii;
use yii\data\ActiveDataProvider;

/**
 * Class CustomIndexAction
 * @package api\common\actions
 */
class CustomUserIndexAction extends \yii\rest\IndexAction
{


    /**
     * 重写父类prepareDataProvider方法。此类相比较于父类IndexAction，允许用户进行复杂搜索，比如，like、in、not in、<、>、>=、<=、
     * between..and..等等的复杂查询。但是需要开发者在modelClass中自定义search方法，并且将要进行搜索的条件在model类中声明，并在
     * rules规则中声明为安全属性，允许外部传入。
     * 示例代码：
     * ```php
     * class Content extends \common\models\Content
     * {
     *      public $keyword;
     *
     *      public function rules()
     *      {
     *          $rules = parent::rules();
     *          $rules[] = [
     *              'keyword','safe'
     *          ];
     *
     *          ...
     *
     *          return $rules;
     *      }
     *
     *          public function search(){
     *              return parent::find()
     *                      ->andFilterWhere(['created_at'=>$this->created_at])
     *                      ->andFilterWhere([
     *                          'or',
     *                          ['like','title',$this->keyword],
     *                          ['like','tags',$this->keyword],
     *                          ['like','content',$this->keyword],
     *                      ]);
     *
     *              }
     *  }
     *
     * ```
     *
     * @return mixed|null|object|\yii\data\DataFilter
     */
    protected function prepareDataProvider()
    {
        $requestParams = Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = Yii::$app->getRequest()->getQueryParams();
        }

        $filter = null;
        if ($this->dataFilter !== null) {
            $this->dataFilter = Yii::createObject($this->dataFilter);
            if ($this->dataFilter->load($requestParams)) {
                $filter = $this->dataFilter->build();
                if ($filter === false) {
                    return $this->dataFilter;
                }
            }
        }

        if ($this->prepareDataProvider !== null) {
            return call_user_func($this->prepareDataProvider, $this, $filter);
        }

        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        //复杂条件搜索
        $model = new $modelClass;
        $model->load($requestParams, 'filter');
        $query = $model->userSearch();

        return Yii::createObject([
            'class' => ActiveDataProvider::className(),
            'query' => $query,
            'pagination' => [
                'params' => $requestParams,
            ],
            'sort' => [
                'params' => $requestParams,
                'enableMultiSort' => true
            ],
        ]);
    }

}